package com.gzist.elderlyserviceplatform.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzist.elderlyserviceplatform.common.base.BaseDTO;
import com.gzist.elderlyserviceplatform.entity.dto.InfoNamePageDTO;
import com.gzist.elderlyserviceplatform.entity.po.Activity;
import com.gzist.elderlyserviceplatform.entity.vo.ActivityListByLatestVO;
import com.gzist.elderlyserviceplatform.mapper.ActivityMapper;
import com.gzist.elderlyserviceplatform.service.ActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 公益活动表 服务实现类
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    /**
     * 根据页码、页大小和活动名称查询活动分页列表
     *
     * @return 返回一个Activity类型的Page对象，包含分页查询结果
     */
    @Override
    public Page<Activity> queryPage(InfoNamePageDTO infoNamePageDTO) {
        // 创建一个LambdaQueryWrapper对象，用于封装查询条件
        LambdaQueryWrapper<Activity> wrapper = Wrappers.lambdaQuery();
        // 添加查询条件：删除标志为0（未删除）且按更新时间降序排序
        wrapper.eq(Activity::getDelFlag, 0).orderByDesc(Activity::getUpdateTime);
        // 如果活动名称非空且不为空字符串，则添加模糊匹配查询条件
        if (StrUtil.isNotBlank(infoNamePageDTO.getName())) {
            wrapper.like(Activity::getName, infoNamePageDTO.getName());
        }
        // 执行分页查询，并返回查询结果
        return this.page(new Page<>(infoNamePageDTO.getPageNum(), infoNamePageDTO.getPageSize()), wrapper);
    }

    @Override
    public List<ActivityListByLatestVO> listActivityLatest() {
        ArrayList<ActivityListByLatestVO> activityListByLatestVOS = new ArrayList<>();
        LambdaQueryWrapper<Activity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Activity::getDelFlag, 0).orderByDesc(Activity::getUpdateTime).last("limit 4");
        List<Activity> queryList = this.list(wrapper);
        queryList.forEach(item -> {
            ActivityListByLatestVO activityListByLatestVO = new ActivityListByLatestVO();
            activityListByLatestVO.setId(item.getId());
            activityListByLatestVO.setName(item.getName());
            activityListByLatestVO.setImage(item.getCover());
            activityListByLatestVO.setDate(DateUtil.format(item.getCreateTime(), "yyyy-MM-dd"));
            activityListByLatestVOS.add(activityListByLatestVO);
        });
        return activityListByLatestVOS;
    }

    @Override
    public Page<Activity> listActivity(BaseDTO baseDTO) {
        return this.page(new Page<>(baseDTO.getPageNum(), baseDTO.getPageSize()));
    }

}
